package com.myapp.web.struts2.components;

import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsException;
import org.apache.struts2.components.ClosingUIBean;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import com.opensymphony.xwork2.util.ValueStack;

@StrutsTag(name="simpleContainer", tldTagClass="com.etrade.web.jsp.ui.SimpleTag", description="the simple container of the template")   
public class SimpleUIBean extends ClosingUIBean { 
	
    public SimpleUIBean(ValueStack stack, HttpServletRequest request,
			HttpServletResponse response) {
		super(stack, request, response);
	}

	private static final Log log = LogFactory.getLog(SimpleUIBean.class);  
	
    private String prefixClass;
    
    public static final String TAG_BODY = "struts2_customizize_$tagBody";
    
	public boolean start(Writer writer) {
		super.evaluateParams();  
        return true;
    }

	public void removeContextValue(){
		Map<String,Object> context = stack.getContext();
	    context.remove(TAG_BODY);		
	}
	
	public boolean end(Writer writer, String body) {              
        try {     
            //super.end(writer, body, false);
        	putContentInContext(body);
            mergeTemplate(writer, buildTemplateName(template, getDefaultTemplate()));
            removeContextValue();
        } catch (Exception e) {
        	log.error(e);
            throw new StrutsException(e);
        }
        finally {
            popComponentStack();
        }
        return false;
    }
	
	public boolean usesBody() {
	    return true;
	}
	
	@Override
	protected void evaluateExtraParams() {
		super.evaluateExtraParams();
		if(prefixClass != null && !"".equals(prefixClass)){
			addParameter("prefixClass", prefixClass);
		}		
	}
	
	private void putContentInContext(String body){
		if(body == null ){
			return ;
		}
		Map<String,Object> map = stack.getContext();
		map.put(TAG_BODY, body);
	}
	
	protected String getDefaultTemplate() {
		return template;
	}

	@Override
	public String getDefaultOpenTemplate() {
		return template;
	}
	
	@StrutsTagAttribute(description="set the prefix of class property of the sytle")
	public void setPrefixClass(String prefixClass) {
		this.prefixClass = prefixClass;
	}
}
